package com.syni.mdd.sjb.common.datatreaure.listen.service;

import com.alibaba.fastjson.JSON;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.DankApplication;
import com.syni.mdd.sjb.common.component.mybatis.dxshapp.entity.DankMerchantsApplication;
import com.syni.mdd.sjb.common.component.utils.common.utils.StringUtils;
import com.syni.mdd.sjb.common.component.utils.feign.service.mddAll.GetConfigService;
import com.syni.mdd.sjb.common.datatreaure.service.DankApplicationService;
import com.syni.mdd.sjb.common.datatreaure.service.DankMerchantsApplicationService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Log4j2
public class DataMerchantAppListener implements ApplicationListener<MerchantsAppEvent> {

    @Autowired
    DankMerchantsApplicationService dankMerchantsApplicationService;
    @Autowired
    DankApplicationService dankApplicationService;
    @Autowired
    GetConfigService getConfigService;

    private final Integer GET_DEFAULT_CONFIG = 106;

    @Override
    @Async
    public void onApplicationEvent(MerchantsAppEvent merchantsAppEvent) {
        Integer userId = merchantsAppEvent.getUserId();
        List<Integer> appIdList = new ArrayList<>();
        Map<String, Object> configMap = getConfigService.GetConfigInfo(GET_DEFAULT_CONFIG);
        if(configMap != null && StringUtils.equals(configMap.get("status").toString(),"00")){
            String configStr = String.valueOf(configMap.get("data"));
            List<String> config = JSON.parseArray(configStr,String.class);
            for(String s : config){
                DankApplication appByName = dankApplicationService.getAppByName(s);
                appIdList.add(appByName.getId());
            }
        }
        DankMerchantsApplication dankMerchantsApplication = dankMerchantsApplicationService.findByUserId(userId);
        if(dankMerchantsApplication == null){
            dankMerchantsApplication = new DankMerchantsApplication();
            dankMerchantsApplication.setAppId(JSON.toJSONString(appIdList));
            dankMerchantsApplication.setUserId(userId);
            dankMerchantsApplicationService.save(dankMerchantsApplication);
        }
    }
}
